package com.example.controller;

import ch.qos.logback.classic.Logger;
import com.alibaba.fastjson.JSON;
import com.example.entity.SysVersion;
import com.example.entity.UserRegId;
import com.example.entity.authority.PartyCheck;
import com.example.entity.authority.SystemUser;
import com.example.entity.authority.UserCheck;
import com.example.entity.authority.UserMetastasis;
import com.example.ext.entity.ExtSysUser;
import com.example.service.*;
import com.example.util.ResultUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by youkun on 2017/8/13.
 */
@RestController
public class UserController {

    private final static Logger logger = (Logger) LoggerFactory.getLogger(UserController.class);

    @Autowired
    private SysUserService userService;

    @Autowired
    private Environment environment;

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private UserRegIdService userRegIdService;

    @Autowired
    private PromotionService promotionService;

    @Autowired
    private ElevatorService elevatorService;

    @Autowired
    PlanDetailService planDetailService;

    @Autowired
    private PartyService parytService;

    @ApiIgnore
    @RequestMapping("/")
    String home() {
        return "Hello World!";
    }

    @ApiOperation(value = "登录接口",notes = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="userName",value="用户名",required = true,dataType = "String"),
            @ApiImplicitParam(name="password",value="密码",required = true,dataType = "String")
    })
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    Map<String,Object> login(@RequestBody  SystemUser login,HttpServletRequest request ) {
        if("1".equals(request.getHeader("x-app"))){
            login.setAppOrPc("App");
        }
         return  userService.findUserByUserName(login);
    }

    @RequestMapping(value = "/getVersion", method = RequestMethod.POST)
    public Map<String, Object> getVersion(@RequestBody Map param) {
        // TODO 2020年7月20发现bug，暂时功能注释
        /*Map res = new HashMap();
        String appversion = param.get("version") + "";
        Map vermap = userService.getVersion();
        if (vermap != null) {
            String versionCode = ((SysVersion) vermap.get("data")).getVersionCode();
            String updateFlag = ((SysVersion) vermap.get("data")).getUpdateFlag();
            String iosurl = ((SysVersion) vermap.get("data")).getIosurl();
            String androidurl = ((SysVersion) vermap.get("data")).getAndroidurl();

            res.put("androidurl", androidurl);
            res.put("iosurl", iosurl);
            if (versionCode.equals(appversion)) {
                res.put("updateFlag", "1");
            } else {
                res.put("updateFlag", updateFlag);
            }
        }
        return ResultUtil.returnSuccess("成功", res);*/
        return ResultUtil.returnError("失败", null);
    }


    @ApiOperation(value = "查询某个用户的信息",notes = "根据用户id获取用户详细信息")
    @ApiImplicitParam(name = "id",value = "用户id",required = true,dataType = "Long",paramType ="path")
    @RequestMapping(value="/api/user/{id}",method = RequestMethod.POST)
    Map<String,Object> user(@PathVariable Long id) {

       return userService.findUserList(id);
    }

    @ApiOperation(value = "查询用户列表的信息",notes = "查询用户列表的信息")
    @RequestMapping(value="/api/user/getUserList",method = RequestMethod.POST)
    Map<String,Object> getUserList(@RequestBody ExtSysUser sysUser){

        return userService.findSysUserList(sysUser);
    }

    /*通过当前用户获取积分信息*/
    @ApiOperation(value = "获取积分信息",notes = "获取积分信息")
    @RequestMapping(value="/api/user/getMarkById",method = RequestMethod.POST)
    Map<String,Object> getMarkById(@RequestBody Map map){
        Long id = Long.valueOf(map.get("id").toString());
        return userService.getMarkById(id);
    }

    @ApiOperation(value = "上传文件",notes = "上传文件")
    @RequestMapping(value="/api/user/upload",method = RequestMethod.POST)
    Map<String,Object> upload(@RequestBody MultipartFile file, HttpServletRequest request){

        return userService.upload(file,request);
    }

    @ApiOperation(value = "上传电梯数据",notes = "上传电梯数据")
    @RequestMapping(value="/api/user/uploadElevators",method = RequestMethod.POST)
    Map<String,Object> uploadElevators(@RequestBody MultipartFile file,@RequestParam("partyId") String partyId){
        return elevatorService.importElevator(file,partyId);
    }

    @ApiOperation(value = "导入计划检查项",notes = "导入计划检查项")
    @RequestMapping(value = "api/user/uploadPlanDetail", method = RequestMethod.POST)
    Map<String, Object> inExcel(@RequestBody MultipartFile file, @RequestParam("id") String planDictId) {
        return planDetailService.inExcel(file, planDictId);
    }

    @ApiOperation(value = "导入机构列表",notes = "导入机构列表")
    @RequestMapping(value="api/user/uploadParty",method = RequestMethod.POST)
    Map<String,Object> importExcelParty(@RequestBody MultipartFile file,@RequestParam("partyId") String parentId){
        return parytService.importExcelParty(file,parentId);
    }

    @ApiOperation(value = "上传大文件",notes = "上传大文件")
    @RequestMapping(value="/api/user/uploadbig",method = RequestMethod.POST)
    Map<String,Object> uploadbig(@RequestBody MultipartFile file, HttpServletRequest request){

        if(file.isEmpty()){
            return ResultUtil.returnError("文件不能空",null);
        }

        String fileName ="";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String dateString = sdf.format(new Date());

        InputStream fis = null;
        BufferedOutputStream stream = null;
        try {

            String path = environment.getProperty("upload",String.class);

            File file1 = new File(path+dateString);
            if(!file1.exists()){
                file1.mkdirs();
            }
            //重现生成文件名，防止中文乱码
            fileName = UUID.randomUUID() + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            //创建文件

            fis = file.getInputStream();
            stream =
                    new BufferedOutputStream(new FileOutputStream(new File(path + dateString + File.separator + fileName)));

            byte[] buffer = new byte[1024 * 1024 * 4];
            int i = -1;
            while ((i = fis.read(buffer)) != -1) {
                stream.write(buffer, 0, i);
            }
        }catch (Exception e){
            logger.error(e.getMessage());
            return ResultUtil.returnError("文件过大上传失败",null);
        }finally {
            try{
                if(fis!=null){
                    fis.close();
                }
            }catch(Exception e){
                logger.error("文件上传流关闭失败");
            }
            try{
                if(stream!=null){
                    stream.close();
                }

            }catch(Exception e){
                logger.error("文件上传流关闭失败");
            }


        }
        return ResultUtil.returnSuccess("上传文件成功",dateString + "/" + fileName);
    }



    @ApiOperation(value = "上传文件",notes = "上传文件")
    @RequestMapping(value="/api/user/uploadRootData",method = RequestMethod.POST)
    Map<String,Object> uploadRootData(@RequestBody MultipartFile file, HttpServletRequest request){

        return userService.uploadRootData(file,request);
    }

    @ApiOperation(value = "获取上传的文件",notes = "获取上传的文件")
    @RequestMapping(value="/user/getUpload/{dateString}/{fileNam:.+}",method = RequestMethod.GET)
    void getUpload(@PathVariable String dateString,@PathVariable("fileNam") String fileName, HttpServletResponse response){

         userService.getImage(dateString,fileName,response);
    }

    @ApiOperation(value = "获取上传的文件",notes = "获取上传的文件")
    @RequestMapping(value="/user/getQrcode/{dicName}/{partyId}/{fileName:.+}",method = RequestMethod.GET)
    void getUploadQrcode(@PathVariable String dicName,@PathVariable String partyId,@PathVariable("fileName") String fileName, HttpServletResponse response){

        userService.getElevatorImage(partyId,fileName,response);
    }



    @ApiOperation(value = "删除上传的文件",notes = "删除上传的文件")
    @RequestMapping(value="/api/user/deleteUpload/{dateString}/{fileNam:.+}",method = RequestMethod.POST)
    void deleteUpload(@PathVariable String dateString,@PathVariable("fileNam") String fileName,HttpServletResponse response) {
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.write(JSON.toJSONString(userService.deleteImage(dateString, fileName)));
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(printWriter!=null){
                printWriter.close();
            }

        }
    }


    @ApiOperation(value = "添加用户",notes = "添加用户")
    @ApiImplicitParams({
            @ApiImplicitParam(name="extSysUser",value="对象",required = true,dataType = "String"),
    })
    @RequestMapping(value = "/api/user/addUser",method = RequestMethod.POST)
    Map<String,Object> add(@RequestBody  ExtSysUser extSysUser) {
        return  userService.addUser(extSysUser);
    }

    @ApiOperation(value = "查询功用户信息",notes = "查询用户详细信息")
    @ApiImplicitParam(name = "id",value = "id",dataType = "String",paramType ="path")
    @RequestMapping(value="/api/user/queryById/{id}",method = RequestMethod.POST)
    Map<String,Object> queryById(@PathVariable(value = "id") String id) {

        return userService.findById(id);
    }

    @ApiOperation(value = "修改用户的信息",notes = "修改用户的信息")
    @RequestMapping(value="/api/user/update",method = RequestMethod.POST)
    Map<String,Object> update(@RequestBody ExtSysUser systemUser) {

        return userService.update(systemUser);
    }

    @ApiOperation(value = "删除用户的信息",notes = "删除用户的信息")
    @RequestMapping(value="/api/user/delete",method = RequestMethod.POST)
    Map<String,Object> delete(@RequestBody Map<String, Object> param) {
        List<String> ids = (List<String>)param.get("ids");
        String partyType = param.get("partyType").toString();
        String partyId = param.get("partyId").toString();
        return userService.delete(ids,partyType,partyId);
    }


    @ApiOperation(value = "查询某个用户的信息",notes = "根据用户id获取用户详细信息")
    @RequestMapping(value="/api/findUserFunction/{id}",method = RequestMethod.POST)
    Map<String,Object> findUserFunction(@PathVariable String id) {

        return userService.findUserFunction(id);
    }

    @ApiOperation(value = "查询某个角色拥有的权限",notes = "查询某个角色拥有的权限")
    @RequestMapping(value="/api/findUserFunctionByRoleId/{id}",method = RequestMethod.POST)
    Map<String,Object> findUserFunctionByRoleId(@PathVariable String id){
        return userService.findUserFunctionByRoleId(id);
    }

    @ApiOperation(value = "查询某个角色拥有的功能权限",notes = "查询某个角色拥有的功能权限")
    @RequestMapping(value="/api/findFuncSID/{name}",method = RequestMethod.POST)
    Map<String,Object> findFuncSID(@PathVariable String name){

        return userService.findFuncSID(name);
    }


    @ApiOperation(value = "查询某个用户拥有的角色",notes = "查询某个用户拥有的角色")
    @RequestMapping(value="/api/findListByUserId/{id}",method = RequestMethod.POST)
    Map<String,Object> findListByUserId(@PathVariable String id)
    {
        return systemRoleService.findListByUserId(id);
    }


    @ApiOperation(value = "查询某个机构下拥有的用户",notes = "查询某个机构下拥有的用户")
    @RequestMapping(value="/api/queryByPartyId/{partyId}",method = RequestMethod.POST)
    Map<String,Object> queryByPartyId(@PathVariable String partyId){
        return userService.queryByPartyId(partyId);
    }

    @ApiOperation(value = "查询某个机构下拥有的用户",notes = "查询某个机构下拥有的用户")
    @RequestMapping(value="/api/queryMainByPartyId/{partyId}",method = RequestMethod.POST)
    Map<String,Object>queryMainByPartyId(@PathVariable String partyId){
        return userService.queryMainByPartyId(partyId);
    }


    @ApiOperation(value = "创建二维码",notes = "创建二维码")
    @RequestMapping(value="/api/createQrcode",method = RequestMethod.POST)
    Map<String,Object> createQrcode(@RequestBody Map qrcodeMap)
    {
        return userService.createQrcode(qrcodeMap.get("elevatorId")+"",qrcodeMap.get("elevatorType")+"",
                qrcodeMap.get("elevatorNum")+"",qrcodeMap.get("partyId")+"");
    }

    @ApiOperation(value = "创建用户设备号",notes = "创建用户设备号")
    @RequestMapping(value="/api/handleUserRegId",method = RequestMethod.POST)
    Map<String,Object> handleUserRegId(@RequestBody UserRegId userReg)
    {

        return userRegIdService.add(userReg);
    }


    @ApiOperation(value = "个人账户注册",notes = "个人账户注册")
    @ApiImplicitParam(value = "实体",paramType = "body",dataType = "UserCheck",name = "userCheck")
    @RequestMapping(value="/register/user",method = RequestMethod.POST)
    Map<String,Object> registerUser(@RequestBody UserCheck userCheck)
    {

        return userService.registerUser(userCheck);
    }

    @ApiOperation(value = "个人账户审核",notes = "个人账户审核")
    @ApiImplicitParam(value = "实体",paramType = "body",dataType = "UserCheck",name = "userCheck")
    @RequestMapping(value="api/check/user",method = RequestMethod.POST)
    Map<String,Object> checkUser(@RequestBody UserCheck userCheck)
    {
        return userService.checkRegisterUser(userCheck);
    }

    @ApiOperation(value = "企业账户注册",notes = "企业注册")
    @ApiImplicitParam(value = "实体",paramType = "body",dataType = "PartyCheck",name = "partyCheck")
    @RequestMapping(value="/register/party",method = RequestMethod.POST)
    Map<String,Object> registerParty(@RequestBody PartyCheck partyCheck)
    {
        return userService.registerParty(partyCheck);
    }


    @ApiOperation(value = "企业账号审核",notes = "企业账号审核")
    @ApiImplicitParam(value = "实体",paramType = "body",dataType = "PartyCheck",name = "partyCheck")
    @RequestMapping(value="api/check/party",method = RequestMethod.POST)
    Map<String,Object> checkRegisterParty(@RequestBody PartyCheck partyCheck)
    {
        return userService.checkRegisterParty(partyCheck);
    }


    @ApiOperation(value = "查询个人用户注册列表",notes = "查询个人用户注册列表")
    @ApiImplicitParam(value = "实体",paramType = "body",dataType = "UserCheck",name = "userCheck")
    @RequestMapping(value="api/queryUserCheckList",method = RequestMethod.POST)
    Map<String,Object> queryUserCheckList(@RequestBody UserCheck userCheck)
    {
        return userService.queryUserCheckList(userCheck);
    }

    @ApiOperation(value = "查询企业用户注册列表",notes = "查询企业用户注册列表")
    @ApiImplicitParam(value = "实体",paramType = "body",dataType = "PartyCheck",name = "partyCheck")
    @RequestMapping(value="api/queryPartyCheckList",method = RequestMethod.POST)
    Map<String,Object> queryPartyCheckList(@RequestBody PartyCheck partyCheck)
    {
        return userService.queryPartyCheckList(partyCheck);
    }


    @ApiOperation(value = "用户找回密码",notes = "用户找回密码")
    @ApiImplicitParam(value = "实体",paramType = "form",dataType = "String",name = "email")
    @RequestMapping(value="api/resetPassword",method = RequestMethod.POST)
    Map<String,Object> resetPassword(@RequestBody Map map)
    {
        String email="";
        if(map.get("email")!=null){
            email = map.get("email").toString();
        }
        return userService.resetPassword(email);
    }


    @ApiOperation(value = "导入人员的信息",notes = "导入人员的信息")
    @RequestMapping(value="api/user/uploadUser",method = RequestMethod.POST)
    Map<String,Object> importPartyPerson(@RequestBody MultipartFile file , @RequestParam("partyId") String partyId,@RequestParam("partyType") String partyType){

        return userService.importPartyPerson(file,partyId,partyType);
    }

    @ApiOperation(value = "人脸识别",notes = "人脸识别")
    @RequestMapping(value="checkFace",method = RequestMethod.POST)
    Map<String,Object>  checkFace(@RequestParam  String userCode,@RequestBody MultipartFile file){
         SystemUser s = new SystemUser();
         s.setUserCode(userCode);
         Map<String,Object> map = userService.checkFace(s,file);
         if(map.get("status").equals(200)){
                //对比成功返回用户信息
                SystemUser user = (SystemUser) map.get("data");
                //查询用户信息返回给前端
                user.setUserName(user.getUserCode());
                return  userService.findUserByUserName(user);
         }
         return map;
    }


    /**
     *
     * @param user
     * id
     * userState
     * @return
     */
    @ApiOperation(value = "更新用户状态",notes = "更新用户状态")
    @RequestMapping(value="/api/user/updateUserState",method = RequestMethod.POST)
    Map<String,Object> updateUserSatte(@RequestBody Map user) {

        return userService.updateUserState(user);
    }

    /**
     *
     * @param userParty
     * userId
     * oldPartyId
     * newPartyId
     * @return
     */
    @ApiOperation(value = "更新用户所属机构",notes = "更新用户状态")
    @RequestMapping(value="/api/user/updateUserParty",method = RequestMethod.POST)
    Map<String,Object> updateUserParty(@RequestBody Map userParty) {

        Map<String,Object> state = userService.updateUserParty(userParty);
        if((state.get("status")+"").equals("200")){
            Map<String,Object> inmap = new HashMap();
            inmap.put("userId",userParty.get("userId"));
            inmap.put("type",userParty.get("type"));
            inmap.put("partyIdAft",userParty.get("newPartyId"));
            inmap.put("partyIdBfr",userParty.get("oldPartyId"));
            inmap.put("partyTypeBfr",userParty.get("partyTypeBfr"));
            inmap.put("partyTypeAft",userParty.get("partyTypeAft"));
            Map<String,Object> state1 = promotionService.empiricTrans(inmap);
        }
        return state;
    }

    /**
     *
     * @param user
     * userId
     * oldPartyId
     * newPartyId
     * @return
     */
    @ApiOperation(value = "更新用户密码",notes = "更新用户密码")
    @RequestMapping(value="/api/user/updateUserPwd",method = RequestMethod.POST)
    Map<String,Object> updateUserPwd(@RequestBody Map user) {

        return userService.updateUserPwd(user);

    }

    /**
     *
     * @param user
     * userId
     * oldPartyId
     * newPartyId
     * @return
     */
    @ApiOperation(value = "更新用户密码",notes = "更新用户密码")
    @RequestMapping(value="/api/user/updateUserPhone",method = RequestMethod.POST)
    Map<String,Object> updateUserPhone(@RequestBody Map user) {
        return userService.updateUserPhone(user);
    }

    @ApiOperation(value = "修改用户图像", notes = "修改用户图像")
    @RequestMapping(value = "/api/user/updatefaceurl", method = RequestMethod.POST)
    Map<String, Object> updateFaceUrl(@RequestBody SystemUser systemUser) {
        return userService.updateFaceUrl(systemUser);
    }

    @ApiOperation(value = "用户转移申请", notes = "用户转移申请")
    @RequestMapping(value = "/api/user/addMeatasis", method = RequestMethod.POST)
    Map<String, Object> addMeatasis(@RequestBody UserMetastasis userMetastasis) {
        return userService.addMeatasis(userMetastasis);
    }

    @ApiOperation(value = "用户转移申请更新", notes = "用户转移申请更新")
    @RequestMapping(value = "/api/user/updateMeatasis", method = RequestMethod.POST)
    Map<String, Object> updateMeatasis(@RequestBody Map param) {
    	String state = param.get("state") + "";
    	if ("2".equals(state)) {
        	updateUserParty(param);
    	}
        return userService.updateMeatasis(param);
    }

    @ApiOperation(value = "用户转移申请查询", notes = "用户转移申请更新")
    @RequestMapping(value = "/api/user/findTomy", method = RequestMethod.POST)
    Map<String, Object> findTomy(@RequestBody UserMetastasis userMetastasis) {
        return userService.findTomy(userMetastasis);
    }


    @ApiOperation(value = "导入电梯台账",notes = "导入电梯台账")
    @RequestMapping(value="/api/user/uploadElevatorLedger",method = RequestMethod.POST)
    Map<String,Object> elevatorLedger(@RequestBody MultipartFile file,String partyId,String partyName){
        return elevatorService.elevatorLedger(file,partyId,partyName);
    }
    @ApiOperation(value = "导入电梯台账",notes = "导入电梯台账")
    @RequestMapping(value="/api/user/uploadElevatorLedgerType",method = RequestMethod.POST)
    Map<String,Object> elevatorTypeLedger(@RequestBody MultipartFile file,String partyId,String partyName){
        return elevatorService.elevatorTypeLedger(file,partyId,partyName);
    }
}
